package com.heishitech.face.controller;

import cn.hutool.core.img.Img;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import com.baidu.aip.face.AipFace;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.Util;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;

/**
 * @author Sheeper
 * @date 2017/10/25.
 */
@RestController
@RequestMapping("aip")
public class AipController {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AipFace aipClient;

    @Value("${aip.addPath}")
    private String addPath;

    @Value("${aip.verifyPath}")
    private String verifyPath;

    @Value("${aip.savePath}")
    private String savePath;

    @Value("${aip.defaultGroup}")
    private String defaultGroup;

    private String separator = System.getProperties().getProperty("file.separator");

    @RequestMapping(value = "/identify", method = RequestMethod.POST)
    public String identifyByImgData(String image) {
        JSONObject res;

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("max_user_num", "1");

        String imageType = "BASE64";
        String groupIdList = defaultGroup;

        // 人脸搜索
        res = aipClient.search(image, imageType, groupIdList, options); //identifyUser(Arrays.asList(defaultGroup), imgPath, options);
        System.out.println(res);
        return res.toString();
    }

    @RequestMapping(value = "/identify/byFile", method = RequestMethod.POST)
    public String identifyByImgPath(String filePath) throws JSONException {
        JSONObject res;
        byte[] imgData;
        try {
            imgData = FileReader.create(FileUtil.file(filePath)).readBytes();
        } catch (Exception e) {
            e.printStackTrace();
            res = new JSONObject();
            res.put("error_code", "-1");
            res.put("error_message", "读取文件失败");
            return res.toString();
        }

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("max_user_num", "1");

        String image = Base64Util.encode(imgData);
        String imageType = "BASE64";
        String groupIdList = defaultGroup;

        // 人脸搜索
        res = aipClient.search(image, imageType, groupIdList, options); //identifyUser(Arrays.asList(defaultGroup), imgPath, options);
        return res.toString();
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(String image, String uid, String userInfo, String groupId) {
        List<String> images = StrUtil.split(image, ',');
        System.out.println(images.get(0));
        if (images.get(0).substring(0, 4).equalsIgnoreCase("data")) {
            return addFace(images.get(1), uid, userInfo, groupId);
        }
        return addFace(image, uid, userInfo, groupId);
    }

    public String addByFile(MultipartFile file, String uid, String userInfo, String groupId) {
        String filePath = addPath + file.getOriginalFilename();
        System.out.println(filePath);

        String image = ImgUtil.toBase64(Img.from(FileUtil.file(filePath)).getImg(), FileUtil.getType(FileUtil.file(filePath)));
        return addFace(image, uid, userInfo, groupId);
    }

    String addFace(String image, String uid, String userInfo, String groupId) {
        JSONObject res;
        if (userInfo == null) {
            userInfo = "";
        }
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "LOW");
        options.put("user_info", userInfo);

        String imageType = "BASE64";

        if (StrUtil.isBlank(uid)) {
            res = new JSONObject();
            try {
                res.put("error_code", "-1");
                res.put("error_msg", "要先写一下你的uid哦~");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return res.toString();
        }
        // 人脸注册
        if (groupId == null || groupId.trim().equals("")) {
            res = aipClient.addUser(image, imageType, defaultGroup, uid, options); //addUser(uid, userInfo, Arrays.asList(defaultGroup), imgPath, options);
        } else {
            res = aipClient.addUser(image, imageType, groupId, uid, options); //addUser(uid, userInfo, Arrays.asList(groupId), imgPath, options);
        }
        System.out.println(res.toString());
        if (res.isNull("error_code")) {
            System.out.println(res.toString());
            return "注册用户成功，快去人脸识别试试吧~";
        } else {
            return res.toString();
        }

    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public String delete(String uid, String group) {
        System.out.println("uid: " + uid);
        System.out.println("groupid: " + group);
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();

        String groupId = group;
        String userId = uid;


        if (uid == null || uid.trim().equals("")) {
            return "{\"error_msg\":\"delete_error\"}";
        }
        JSONObject res;
        if (group == null || group.trim().equals("")) {
            res = aipClient.deleteUser(defaultGroup, userId, options);  //deleteUser(uid, Arrays.asList(defaultGroup));
        } else {
            // 删除用户组
            res = aipClient.groupDelete(groupId, options); //deleteUser(uid, Arrays.asList(group));
        }

        return res.toString();
    }

    @RequestMapping(value = "/find", method = RequestMethod.POST)
    public String find(String group) {
        HashMap<String, String> options = new HashMap<String, String>(2);
        HashMap<String, String> option = new HashMap<String, String>(2);
        options.put("start", "0");
        options.put("num", "100");
        JSONObject res;
        if (group == null || group.trim().equals("")) {
            res = aipClient.getGroupList(options);
        } else if (".".equals(group)) {
            res = aipClient.getGroupUsers(defaultGroup, option);
        } else {
            res = aipClient.getGroupUsers(group, option);
        }

        return res.toString();
    }


    @RequestMapping(value = "/savePicture", method = RequestMethod.POST)
    public String savePicture(String img) {
        String imgPath = savePath + separator + System.currentTimeMillis() + ".png";
        byte[] imgBytes = Base64.decodeBase64(img);
        try {
            Util.writeBytesToFileSystem(imgBytes, imgPath);
        } catch (Exception e) {
            log.error(e.toString());
            return "{\"error_code\":\"save_error\"}";
        }
        return "{\"log_id\":\"save_success\"}";
    }

    @RequestMapping(value = "/detect", method = RequestMethod.POST)
    public String detect(String image) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();
        options.put("face_field", "age,beauty,expression,faceshape,gender,glasses,landmark,race,quality,facetype");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");

        //String image = image;
        String imageType = "BASE64";

        // 人脸检测
        JSONObject res = aipClient.detect(image, imageType, options);
        System.out.println(res.toString());
        return res.toString();
    }

    @RequestMapping(value = "/get", method = RequestMethod.POST)
    public String getUser(String userId, String groupId) {
        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<>();

        //String userId = "user1";
        //String groupId = "group1";

        // 用户信息查询
        JSONObject res = aipClient.getUser(userId, groupId, options);
        System.out.println(res.toString());

        return res.toString();
    }

}
